package com.gitee.wsl.collections.list

import com.gitee.wsl.base.Option
import com.gitee.wsl.base.ofNullable

class LazyArrayList<T>(override val size: Int):BaseList<T> {

    constructor(baseList: List<T>):this(baseList.size){
        baseList.forEachIndexed {index, t -> set(index,t)  }
    }

    private val cache = arrayOfNulls<Any>(size)

    override fun get(index: Int): T {
       return cache[index]!! as T
    }

    operator fun set(index: Int,value:T){
        cache[index] = value
    }

    fun safeGet(index: Int):Option<T>{
        return Option.ofNullable(cache[index] as T?)
    }

    fun getOrNull(index: Int): T? {
        return cache[index] as T?
    }

    fun checkValue():Boolean = !cache.contains(null)

    fun toArray():Array<T> {
        return cache as Array<T>
    }
}

inline fun <reified T> lazyArray(comp: Int) = LazyArrayList<T>(comp)

inline fun <reified T> lazyArray2(comp: Int) = LazyArrayList<LazyArrayList<T>>(comp)

fun<E> List<E>.toArray() = LazyArrayList(this).toArray()

fun<E> Collection<E>.toArray()= toList().toArray()